package com.boot.config.shiro;

import com.boot.model.Permission;
import com.boot.model.Role;
import com.boot.model.User;
import com.boot.service.PermissionService;
import com.boot.service.RoleService;
import com.boot.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: zhengshunzhi
 * @Date: 2018/8/30 14:56
 * @Description: shiro自定义realm
 * 实现AuthorizingRealm接口用户用户认证
 */
public class MyShiroRealm extends AuthorizingRealm {

    //用户名查询
    @Autowired
    private UserService userService;

    //角色查询
    @Autowired
    private RoleService roleService;

    //权限查询
    @Autowired
    private PermissionService permissionService;

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken tk = (UsernamePasswordToken) token;
        String username = tk.getUsername();
        User user = userService.findUserByName(username);
        System.out.println("shiro认证 user ->" + user);
        if (user == null) {
            //这里返回后会报出对应异常
            return null;
        }
        //这里验证authenticationToken和simpleAuthenticationInfo的信息
        return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取登录用户
        User user = (User) principals.getPrimaryPrincipal();
        //根据用户id查询角色
        List<Role> roles = roleService.findRolesByUid(user.getId());
        System.out.println("roles -> " + roles);

        List<String> rList = new ArrayList<String>();////用户的角色集合
        List<String> pList = new ArrayList<String>();//用户的权限集合

        roles.forEach(r -> {
            if (r != null) {
                rList.add(r.getName());//添加角色名称
                List<Permission> permissions = permissionService.findPermissionsByRid(r.getId());
                System.out.println("permissions -> " + permissions);
                permissions.forEach(p -> {
                    if (p != null) {
                        pList.add(p.getName());
                    }
                });
            }
        });

        //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //用户的角色集合
        info.addRoles(rList);
        //用户的权限集合
        info.addStringPermissions(pList);

        return info;
    }
}
